<?php
	if(!isset($_SESSION)){
		session_start();
	}
	
	// Clear previous messages.
	if(isset($_SESSION['error'])) unset($_SESSION['error']);
	if(isset($_SESSION['success'])) unset($_SESSION['success']);
	
	$i=0;
	$num = $_SESSION['num'];
	$flag = 0;
	
	while ($i <  $num){
		$itemCode = $_POST['itemCode'.$i];
		if($itemCode != ''){	
			include("../dbconnection.php");
			$batchId = $_POST['batchId'.$i];
			$MFD = $_POST['mfd'.$i];
			$EXP = $_POST['exp'.$i];		
			$boughtPrice = $_POST['boughtPrice'.$i];
			$unitPrice = $_POST['unitPrice'.$i];
			$stockQuantity = $_POST['quantity'.$i];
			
			if($result = mysql_query("select itemCode from stock where itemCode='$itemCode' and batchId='$batchId'")){
				if(mysql_num_rows($result) > 0){
					$duplicate[] = $itemCode;
					$_SESSION['error'] = "Duplicate entry with item code ".join(', ',$duplicate);
				}else{
					if(mysql_query("INSERT INTO stock (itemCode, batchId, MFD, EXP, unitPrice, boughtPrice, stockQuantity) VALUES ('$itemCode', '$batchId','$MFD', '$EXP','$unitPrice','$boughtPrice', '$stockQuantity')")){
						if(empty($duplicate))
							$_SESSION['success'] = "Item added to the stock successfully";
						else
							$_SESSION['success'] = "Item added to the stock successfully. But Duplicate entry with item code ".join(', ',$duplicate);
						$_SESSION['page'] = "addStock.php";
						if($flag == 0)
							$flag = 1;					
					}else{
						$_SESSION['error'] = "Error occured!";
						$_SESSION['page'] = "addStock.php";
					}
				}
			}else{
				$_SESSION['error'] = "Error occured";
				$_SESSION['page'] = "addStock.php";
			}
		}
		$i++;
	}
	header('Location: ../../');	
?>	
			